package com.qilu.handler;

import com.alibaba.fastjson.JSON;
import com.qilu.domain.R;
import com.qilu.util.JwtUtils;
import com.qilu.util.WebUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Slf4j
public class LoginHandler implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        String token = JwtUtils.getTokenByRequest(request);
        if(StringUtils.isBlank(token)){
            WebUtils.renderString(response, JSON.toJSONString(R.error(401,"请重新登录")));
            return false;
        }
        Claims claims = JwtUtils.getClaimByToken(token);
        if(Objects.isNull(claims)){
            WebUtils.renderString(response, JSON.toJSONString(R.error(401,"请重新登录")));

            return false;
        }
        return true;
    }
}
